/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "framework/cutils.h"

#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h> /* See NOTES */
#include <time.h>
#include <unistd.h>

#define NANOSEC 1000000000
#define MICROSEC 1000000

void SysTimeMs(uint32_t *sec, uint32_t *ms) {
  struct timespec ti;
  clock_gettime(CLOCK_REALTIME, &ti);
  *sec = (uint32_t)ti.tv_sec;
  *ms = (uint32_t)(ti.tv_nsec / 1000000);
}

uint64_t GetTimeMs() {
  uint64_t t;
  struct timespec ti;
  clock_gettime(CLOCK_MONOTONIC, &ti);
  t = (uint64_t)ti.tv_sec * 1000;
  t += ti.tv_nsec / 1000000;
  return t;
}

bool SetSockRecvTimeout(int fd, int timeout_ms) {
  struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
  return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout,
                         sizeof(timeout));
}

bool SetNonBlock(int fd, bool b) {
  int flags = fcntl(fd, F_GETFL, 0);
  if (b) {
    flags |= O_NONBLOCK;
  } else {
    flags &= ~O_NONBLOCK;
  }
  return fcntl(fd, F_SETFL, flags) != -1;
}

bool IsBlock(int fd) {
  int flags = fcntl(fd, F_GETFL, 0);
  return !(flags & O_NONBLOCK);
}

const char *GetError() { return strerror(errno); }
